# -*- coding: utf-8 -*-
#! /bin/env python

"""This Program rename molecular model file by its formula
Usage: ren2for.py *.msd
"""

from dffpy import *
from sys import argv
import os
import os.path
from shutil import move



RECURSIVE = False
SILENCE  = False
PATTERN = "%s_%d%s"
COUNTER = 0

def extname(name):
    index = name.rfind(".")
    if index == -1:
        return ""
    else:
        return name[index:]
    
def rename_file_by_formula(filename, formula):
    global COUNTER
    path, name = os.path.split(filename)
    name = extname(name)
    COUNTER += 1
    name = PATTERN % (formula, COUNTER, name)
    fullname = os.path.join(path, name)
    move(filename, fullname)
    if not SILENCE:
        print filename, "-->", fullname
    
    
def rename_file(filename):
    try:
        mol = MolecularModel.read(filename)
        formula = mol.formula
        if formula:
            rename_file_by_formula(filename, formula)
        else:
            raise Exception()
    except Exception, error:
        if not SILENCE:
            print error
            print "Failed to read molecular information from file ", filename

def rename_folder(root):
    assert os.path.isdir(root)
    for i in os.listdir(root):
        fullname = os.path.join(root, i)
        if os.path.isfile(fullname):
            rename_file(fullname)
        elif RECURSIVE and os.path.isdir(fullname):
            rename_folder(fullname)

        
def rename(root):
    if os.path.isdir(root):
        rename_folder(root)
    elif os.path.isfile(root):
        rename_file(root)
    else:
        (path, name) = os.path.split(root)
        if not path:
            path = "."
        from glob import glob
        for i in glob(root):
            fullname = os.path.join(path, i)
            if os.path.isdir(fullname):
                rename_folder(fullname)
            else:
                rename_file(fullname)
    
if __name__ == '__main__':
    if len(argv) == 1:
        print __doc__
    else:
        for i in argv[1:]:
            if i == "-r" or i == "-R":
                RECURSIVE = True
            elif i == "-s" or i == "-S":
                SILENCE  = True
            else:
                rename(i)
